package com.alit.face.koala.listener;

import java.io.File;
import java.net.URL;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import com.alit.face.koala.mq.apacheapollo.MQTTSender;
import com.alit.face.koala.projectvariable.PVK;
import com.litong.utils.projectvariable.PVU;

import lombok.extern.slf4j.Slf4j;

/**
 * @author litong
 * @date 2019年5月10日_上午11:01:11
 * @version 1.0
 */
@Component
@Slf4j
public class InitConfiguration implements ApplicationListener<ContextRefreshedEvent> {
  @Autowired
  private Environment environment;

  @Override
  public void onApplicationEvent(ContextRefreshedEvent event) {
    /**
     * staticLocation的值
     * eclipse中:classpath:/alit-face-koala
     * linux中:file:./alit-face-koala
     * linux中:file:/opt/springboot/alit-face-koala-1.0/alit-face-koala
     */
    String staticLocations = environment.getProperty("spring.resources.static-locations");
    log.info("staticLocation:" + staticLocations);
    setUploadFolder(staticLocations);
    initConnection();
  }

  /**
   * 初始化连接
   */
  private void initConnection() {
    MQTTSender.init();
  }

  /**
   * 设置文件上传目录
   * @param staticLocation
   */
  private void setUploadFolder(String staticLocations) {
    String uploadDirName = PVU.getValue(PVK.projectUploadDirName);
    String[] typeAndLocations = staticLocations.split(":");
    String[] locations = typeAndLocations[1].split(",");
    String staticPath = null;
    if (typeAndLocations[0].startsWith("file")) {
      staticPath = new File(locations[0]).getAbsolutePath();
    } else {
      URL resource = this.getClass().getResource(locations[0]);
      staticPath = resource.getFile();
    }
    File uploadFolder = new File(staticPath + File.separator + uploadDirName);
    PVU.add(PVK.projectStaticPath, "静态文件存放目录", staticPath, false, false);
    PVU.add(PVK.projectImgDir, "图片保存目录", uploadFolder.getAbsolutePath(), false, false);
    if (!uploadFolder.exists()) {
      log.info("图片保存目录不不存在,创建图片保存目录:"+uploadFolder.getAbsolutePath());
      uploadFolder.mkdirs();
    }else{
      log.info("图片保存目录存在,无需创建:"+uploadFolder.getAbsolutePath());
    }
  }
}
